﻿using System;
using System.Diagnostics;
using System.ServiceProcess;

public class MySQLServiceStarter
{
    // MySQL 服务名称，通常为 MySQL 或 MySQL80 等，需根据实际情况修改
    private const string MySQLServiceName = "MySql3306";

    public static void StartMySQLService()
    {
        try
        {
            using (ServiceController serviceController = new ServiceController(MySQLServiceName))
            {
                // 检查服务是否存在
                try
                {
                    // 尝试获取服务状态，若不存在会抛出异常
                    ServiceControllerStatus status = serviceController.Status;
                }
                catch (InvalidOperationException)
                {
                    Console.WriteLine($"错误：未找到 MySQL 服务 '{MySQLServiceName}'。请确认服务名称是否正确。");
                    return;
                }

                // 根据服务当前状态进行相应操作
                switch (serviceController.Status)
                {
                    case ServiceControllerStatus.Running:
                        Console.WriteLine("MySQL 服务已在运行中。");
                        return;

                    case ServiceControllerStatus.StartPending:
                        Console.WriteLine("MySQL 服务正在启动中，请稍候...");
                        WaitForServiceStatus(serviceController, ServiceControllerStatus.Running);
                        Console.WriteLine("MySQL 服务已成功启动。");
                        return;

                    case ServiceControllerStatus.Stopped:
                        Console.WriteLine("正在启动 MySQL 服务...");
                        serviceController.Start();
                        serviceController.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(30));
                        Console.WriteLine("MySQL 服务已成功启动。");
                        return;

                    default:
                        Console.WriteLine($"MySQL 服务当前状态为 {serviceController.Status}，尝试停止后重启...");
                        try
                        {
                            if (serviceController.Status != ServiceControllerStatus.Stopped &&
                                serviceController.Status != ServiceControllerStatus.StopPending)
                            {
                                serviceController.Stop();
                                serviceController.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(30));
                            }
                            serviceController.Start();
                            serviceController.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(30));
                            Console.WriteLine("MySQL 服务已成功重启。");
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"重启 MySQL 服务失败：{ex.Message}");
                        }
                        return;
                }
            }
        }
        catch (Exception ex)
        {
            // 记录详细异常信息
            Console.WriteLine($"启动 MySQL 服务时发生错误：{ex.Message}");
            if (ex.InnerException != null)
            {
                Console.WriteLine($"内部异常：{ex.InnerException.Message}");
            }

            // 备选方案：使用命令行启动服务
            TryStartServiceViaCommandLine();
        }
    }

    private static void TryStartServiceViaCommandLine()
    {
        try
        {
            using (Process process = new Process())
            {
                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    FileName = "sc.exe",
                    Arguments = $"start {MySQLServiceName}",
                    Verb = "runas", // 请求管理员权限
                    UseShellExecute = true,
                    CreateNoWindow = true
                };

                process.StartInfo = startInfo;
                process.Start();
                process.WaitForExit(10000); // 等待 10 秒

                if (process.ExitCode == 0)
                {
                    Console.WriteLine("通过命令行成功启动 MySQL 服务。");
                }
                else
                {
                    Console.WriteLine($"命令行启动 MySQL 服务失败，退出代码：{process.ExitCode}");
                    Console.WriteLine("请确保应用程序以管理员权限运行。");
                }
            }
        }
        catch (Exception cmdEx)
        {
            Console.WriteLine($"命令行启动 MySQL 服务时发生错误：{cmdEx.Message}");
            Console.WriteLine("请手动启动 MySQL 服务或检查服务配置。");
        }
    }

    private static void WaitForServiceStatus(ServiceController serviceController, ServiceControllerStatus desiredStatus)
    {
        int maxRetries = 10;
        int retryCount = 0;

        while (retryCount < maxRetries)
        {
            serviceController.Refresh();
            if (serviceController.Status == desiredStatus)
            {
                return;
            }

            System.Threading.Thread.Sleep(1000);
            retryCount++;
        }

        Console.WriteLine($"等待服务状态超时，当前状态：{serviceController.Status}");
    }
}